<?php

/**
 * 
 * 兑换确认 Model
 * @author alang
 *
 */

class api_exchange_confirm_mdl extends Base_Controller
{
	const TBL_LOTTERY = 'cj_lottery';
	
	public function __construct()
	{
		parent::__construct();
		$this->load->model('login_mdl','login');
	}
	
	/**
	 * 
	 * 输出
	 * @param Array $data
	 */
	public function outputdata($data)
	{
		header('Content-Type:text/html; charset=utf-8', false);
		
		//检查参数
		if(empty($data['REWARDID']) || empty($data['USERID']) || empty($data['RNUM']) || empty($data['PRODUCTID']) || empty($data['EXCHANGEID'])){
			
			$tmp['TAG'] = $data['TAG'];
			$tmp['STATUS'] = 1;
			$tmp['USERINFO'] = '';
			$tmp['ERRORMESSAGE'] = 'INFO ERROR';
			echo json_encode($tmp);
			exit;
		
		}
		//验证登陆
		if(!$this->login->_checklogin($data['USERID'],$data['EMAIL'],$data['TOKEN'])) {
			
			$tmp['TAG'] = $data['TAG'];
			$tmp['STATUS'] = 10001;
			$tmp['USERINFO'] = '';
			$tmp['ERRORMESSAGE'] = 'NO LOGIN';
			echo json_encode($tmp);
			exit;
			
		}
		
		$result = $this->_check_exchange($data['REWARDID'],$data['USERID'],$data['RNUM'],$data['PRODUCTID'],$data['EXCHANGEID']);
		
		if(empty($result)){
			
			$tmp['TAG'] = $data['TAG'];
			$tmp['STATUS'] = 1;
			$tmp['USERINFO'] = null;
			$tmp['ERRORMESSAGE'] = 'none';
			
		}else{
			
			$updatedata['exchangestate'] = 3;
			if($this->_change_state($data['EXCHANGEID'],$updatedata)){
				$tmp['TAG'] = $data['TAG'];
				$tmp['STATUS'] = 0;
				$tmp['USERINFO'] = null;
				$tmp['ERRORMESSAGE'] = 'successful';
			}else{
				//已兑奖或系统出错
				$tmp['TAG'] = $data['TAG'];
				$tmp['STATUS'] = 1;
				$tmp['USERINFO'] = null;
				$tmp['ERRORMESSAGE'] = 'haved';
			}
		}
		echo json_encode($tmp);
	}
	
	
	/**
	 * 检查兑奖信息
	 */
	private function _check_exchange($rewardid,$uid,$rnum,$productid,$id)
	{
		$lottery = $this->db->select('exchange.id,exchange.rewardid,exchange.productid,exchange.rnum,exchange.uid,exchange.lotteryid')
						->from('cj_exchange as exchange')
						->where('exchange.lotteryid',$id)
						->get()
						->row_array();
		return $lottery;
	}
	
	/**
	 * 改变兑奖状态
	 */
	
	private function _change_state($id,$data)
	{
		$this->db->where('lotteryid', $id);
		$this->db->update('cj_exchange', $data);
		//echo $this->db->affected_rows();
		return $this->db->affected_rows();
	}
	
}